#include "activity_list_view.h"
#include "ui_activity_list_view.h"

#include "activity_view.h"

ActivityListView::ActivityListView(QWidget *parent) :
    ViewBase(parent),
    ui(new Ui::ActivityListView),
    activityView_(0)
{
    ui->setupUi(this);
    QAction *backSoftkeyAction = new QAction(QString("Back"), this);
    backSoftkeyAction->setSoftKeyRole(QAction::NegativeSoftKey);
    QObject::connect(backSoftkeyAction, SIGNAL(triggered()),
                     this, SLOT(close()));
    addAction(backSoftkeyAction);
    connect(ui->lstActivityList, SIGNAL(itemActivated(QListWidgetItem*)),
            this, SLOT(showActivity(QListWidgetItem*)));
}

ActivityListView::~ActivityListView()
{
    delete ui;
    if (activityView_) {
      delete activityView_;
    }
}

void ActivityListView::IssueRequest() {
  QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));
  RequestMethod request(this, QString("xml"), QString("Activities.getByCategory"));
  request.AddParam(QString("category"), category_.cn_cate);
  request.AddParam(QString("city"), QString("北京"));

  activities_.clear();

  ui->lstActivityList->clear();

  if (handler_) {
    handler_->IssueRequest(request);
  }
}

int ActivityListView::ProcessResult(RequestMethod &, QDomElement &e) {
  int re = parse_result(e);
  if (re == 0) {
    for (int i = 0; i < activities_.count(); ++i) {
      activity &a = activities_[i];
      ui->lstActivityList->addItem(a.name);
    }
  }

  return re;
}


int ActivityListView::parse_result(QDomElement &e) {
  QDomNodeList l = e.childNodes();
  for (int i = 0; i < l.count(); ++i) {
    QDomElement el = l.at(i).toElement();
    if (el.nodeName() == QString("activities")) {
      parse_activities(el);
    }
  }

  return 0;
}

int ActivityListView::parse_activities(QDomElement &e) {
  QDomNodeList l = e.childNodes();
  for (int i = 0; i < l.count(); ++i) {
    QDomElement el = l.at(i).toElement();
    if (el.nodeName() == QString("activity")) {
      activity a;
      parse_activity(el, a);
      activities_.push_back(a);
    }
  }

  return 0;
}

void ActivityListView::showActivity(QListWidgetItem *item) {
  for (int i = 0; i < activities_.count(); ++i) {
    activity &a = activities_[i];
    if (a.name == item->text()) {
      if (!activityView_) {
        activityView_ = new ActivityView(this);
        activityView_->SetRequestHandler(handler_);
      }

      activityView_->Show();
      activityView_->SetActivity(a);
      activityView_->IssueRequest();

      return;
    }
  }
}
